package com.tt5.services.vertx.json

import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.MapperFeature
import com.fasterxml.jackson.databind.SerializationFeature
import io.vertx.core.json.jackson.DatabindCodec
import io.vertx.core.json.jackson.JacksonCodec
import io.vertx.core.spi.json.JsonCodec

class JacksonFactory : io.vertx.core.spi.JsonFactory {
  companion object {
    @JvmStatic
    val INSTANCE = JacksonFactory()
    val CODEC: JsonCodec by lazy {
      try {
        DatabindCodec.mapper()
          // 属性名忽略大小写
          .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
          // 忽略 transient 修饰的属性
          .configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true)
          // 反序利化时忽略未知字段
          .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
          // 序利化时枚举值使用 ordinal 值
          .configure(SerializationFeature.WRITE_ENUMS_USING_INDEX, true)
          .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
          // 序利化时忽略null对象
          .setSerializationInclusion(JsonInclude.Include.NON_NULL)
        DatabindCodec()
      } catch (_: Throwable) {
        // No databind
        JacksonCodec()
      }
    }
  }

  override fun codec(): JsonCodec {
    return CODEC
  }
}
